package rule;

import com.alibaba.fastjson.JSON;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.jeasy.rules.core.RulesEngineParameters;
import org.jeasy.rules.mvel.MVELRule;

/**
 * @author dushougudu
 */
public class EasyRules {
    @Rule(name = "weather rule1", description = "simple rule1", priority = 2)

    public static class WeatherRule1 {
        @Condition
        public boolean when(@Fact("rain") boolean rain) {
            return rain;
        }

        @Action
        public void then() {
            System.out.println("It rains, with rule1 .");
        }
    }

    @Rule(name = "weather rule2", description = "simple rule2", priority = 1)
    public static class WeatherRule2 {
        @Condition
        public boolean when(@Fact("rain") boolean rain) {
            return false;
        }

        @Action
        public void then() {
            System.out.println("It rains, with rule2 .");
        }
    }

    public static void main(String[] args) throws Exception {
        Rules rules = new Rules();

        org.jeasy.rules.api.Rule ageRule = new MVELRule()
                .name("age rule")
                .description("Check if person's age is > 18 and marks the person as adult")
                .priority(1)
                .when("person.age > 18")
                .then("person.setAdult(true);person.setName(\"james\");");

        Person tom = new Person("Tom", 19);

        rules.register(new WeatherRule1());
        rules.register(new WeatherRule2());
        rules.register(ageRule);

        Facts facts = new Facts();
        facts.put("rain", true);
        facts.put("person", tom);

        RulesEngineParameters parameters = new RulesEngineParameters()
                .skipOnFirstAppliedRule(true)
                .skipOnFirstFailedRule(true)
                .skipOnFirstNonTriggeredRule(true);

        RulesEngine rulesEngine = new DefaultRulesEngine();
        rulesEngine.fire(rules, facts);
        System.out.println(JSON.toJSONString(tom));
    }
}
